<template>
  <el-dialog
    v-el-drag-dialog
    class="showDialog"
    :title="title"
    :visible="visible"
    width="900px"
    @close="clearTemp"
    :close-on-click-modal="false"
    @update:visible="updateVisible"
    :append-to-body="appendToBody">
    <div v-if="self_form" class="show-box">
      <!-- 基本信息区 -->
      <div @click="leftClick" class="left">
        <div class="info-row">
          <div class="show-name-input">
            <span style="flex-shrink: 0; padding-right: 15px;">{{ $t('节目名称') }}</span>
            <!-- <el-input :disabled="opType === '3'" @click.prevent.stop="()=>{}" style="width: 320px;" v-model="self_form.name" clearable></el-input> -->
            <el-input @click.prevent.stop="()=>{}" style="width: 320px;" v-model="self_form.name" clearable></el-input>
          </div>
          <el-button size="small" v-if="opType === '1'" type="primary" @click.stop="_openTempDialog" style="min-width:100px;">{{ $t('选择模版') }}</el-button>
          <el-select-tree
            v-if="opType === '3'"
            class="full-width"
            v-model="self_form.folderId"
            :disabled-values="[initFoldId, -1]"
            :default-expand-all="defaultExpandAll"
            :check-strictly="true"
            :placeholder="$t('请选择')"
            :data="treeData"
            :clearable="true"
            :props="{
              value: 'id',
              label: 'name',
              userId: 'userId',
              children: 'children'
            }"
            :ollie-disabled="true"
            @change="selectTreeChange">
          </el-select-tree>
          <el-button size="small" v-if="opType !== '4'" style="margin-left: 15px;" type="primary" @click.stop="okClick">{{ $t('确定') }}</el-button>
          <el-button size="small" style="margin-left: 15px;" @click.stop="cancelClick">{{ $t('取消') }}</el-button>
        </div>
        <!-- 模版预览 --> 
        <template-main
          ref="templateMain"
          :twidget="twidget"
          :template-opts="templateOpts"
          @widgetClick="widgetClick"></template-main>
      </div>
      <!-- 属性区 -->
      <div class="right">
        <div class="info-row attr-title">
          {{ $t('属性') }}
        </div>
        <div class="element-name">
          {{ infoTitle }}
        </div>
        <div v-if="currInfo.form">
          <temp-form
            v-if="!currInfo.areaId"
            :form="currInfo.form"></temp-form>
          <background-form
            v-else-if="currInfo.areaId === 'Background'"
            :form="currInfo.form"></background-form>
          <clock-form
            v-else-if="currInfo.areaId === 'Date'"
            :form="currInfo.form"></clock-form>
          <timing-form
            v-else-if="currInfo.areaId === 'Time'"
            :form="currInfo.form"></timing-form>
          <list-like-form
            v-else
            :form="currInfo.form"
            :area-id="currInfo.areaId"
            :program-media="currProgramMedia"
            @chooseMedia="chooseMedia"></list-like-form>
        </div>
      </div>
    </div>

    <!-- 模版选择弹窗 -->
    <temp-dialog
      :visible.sync="temDialog.show"
      @close="initTemplateInfo"></temp-dialog>

  </el-dialog>
</template>

<script>
import { createNamespacedHelpers } from 'vuex'
const { mapGetters } = createNamespacedHelpers('media')

import TempForm from './Form/TempForm'
import BackgroundForm from './Form/BackgroundForm'
import ListLikeForm from './Form/ListLikeForm'
import ClockForm from './Form/ClockForm'
import TimingForm from './Form/TimingForm'
import TempDialog from './TempDialog'

import TemplateMain from '../../components/TemplateMain'

import {widgetNameMap} from '../const'

export default {
  components: {
    TempForm,
    BackgroundForm,
    ListLikeForm,
    ClockForm,
    TimingForm,
    TempDialog,
    TemplateMain
  },
  props: {
    appendToBody: {
      type: Boolean,
      default: false
    },
    visible: {
      type: Boolean,
      default: false
    },
    form: {
      type: Object,
      default() {
        return null
      }
    },
    opType: {
      type: String,
      default: '1' // 1 添加 2 编辑 3 另存 4 查看
    },
    id: {
      type: String,
      default: ''
    }
  },
  provide() {
    return {
      dialogId: this.id
    }
  },
  data() {
    return {
      self_form: null,
      showName: '',
      tempInfo: null,
      currInfo: {
        areaId: '',
        form: null
      },
      temDialog: {
        show: false
      },
      twidget: [
        // {"w":"4000,85.6%","h":"2800,73.99%","x":"0,0%","y":"0,0%","name":"背景","type":"Bg","zindex":"8","index":"0"},{"w":"3000,27%","h":"2000,33%","x":"282,26.18%","y":"106,9.82%","name":"直播区","type":"Anchor","zindex":"10","index":"0"}
      ],
      templateOpts: {
        width: 4000,
        height: 4000
      },
      templateForm: {},
      currWidget: null, // 当前聚焦的部件
      programMedia: [], // 节目模版区域的媒体素材
      currProgramMedia: null, // 当前正在编辑的媒体素材表
      initFoldId: '', // 当前目录
      defaultExpandAll: true
    }
  },
  computed: {
    ...mapGetters(['menuTreeNoOther']),
    treeData() {
      return this.menuTreeNoOther(3)
    },
    title() {
      const opNames = ['', '添加节目', '编辑节目', '另存节目', '查看节目']
      return this.$t(opNames[this.opType]) 
    },
    infoTitle() {
      return this.currInfo.areaId ? widgetNameMap[this.currInfo.areaId.split('-')[0]] : this.$t('模板')
    },
    widgetMap() {
      let map = {}
      this.twidget.forEach(item => {
        map[`${item.type}-${item.index}`] = item
      })
      return map
    }
  },
  watch: {
    form(v) {
      if (!v) {
        this.self_form = null
      } else {
        this.self_form = {
          ...v,
          name: v.name.replace(/\.pgm$/, '')
        }
        if (this.opType === '2' || this.opType === '3' || this.opType === '4') {
          this.$nextTick(() => {
            this.initTemplateInfo({
              argus: v.templateArgus,
              name: v.templateName,
              type: v.templateType,
              width: v.templateWidth,
              height: v.templateHeight,
              id: v.templateId
            })
          }) 
        }
        if (this.opType === '3') {
          // this.initFoldId = v.folderId
          this.self_form.folderId = ''
        }
        console.log(this.self_form)
      }
    },
    widgetMap(v) { // 监听此模版所有区域  生成有媒体列表的区域数组programMedia
      if (this.opType !== '1') { // 如果不是新增窗口 就在传入的表单里面拿
        // TODO 看情况需不需要在这手动初始化而不是直接从后台数据拿
        this.programMedia = this.self_form.programMedia.slice()
        console.log(this.programMedia)
      } else { // 新增窗口需要自己初始化
        let arr = []
        let noAreaId = ['Background', 'Weather', 'Clock', 'Timer'] // 没有素材列表的区域
        for(const prop in v) {
          const type = prop.split('-')[0]
          if (noAreaId.indexOf(type) === -1) {
            arr.push({
              areaId: prop,
              mediaArgus: []
            })
          }
        }
        this.programMedia = arr
      }
    }
  },
  methods: {
    selectTreeChange(id, data) {
      if (data.id === -1) {
        this.$alert('提示', '此目录不能操作')
        this.self_form.folderId = 0
        return
      }
      this.self_form.folderId = data.id ? data.id : 0
      if (data._isSub && data.ownerUserId) {
        this.self_form.ownerUserId = data.ownerUserId
      } else {
        delete this.self_form.ownerUserId
      }
    },
    clearTemp() {
      this.templateOpts = {
        width: 4000,
        height: 4000
      }
      this.templateForm = {}
      this.currWidget = null
      this.programMedia = []
      this.currProgramMedia = null
      this.currInfo = {
        areaId: '',
        form: null
      }
      setTimeout(() => {
        this.$refs.templateMain.__resetWidget()
      }, 500)
    },
    leftClick() {
      this.widgetClick(false)
    },
    chooseMedia(media) {
      // TODO: 判断所选media类型 设置好elementOpts
      const elementOpts = {
        type: 'video',
        url: 'https://encrypted-vtbn0.gstatic.com/video?q=tbn:ANd9GcR-zef6tJV37x6qG9DqE1JaSuPGkqeoDyLeOrjMP3W7NfQ6I6jF'
      }
      this.$refs.templateMain.__widgetSetElement(this.currWidget, elementOpts)
    },
    widgetClick(widget) {
      if (widget === false) { // 模板模式
        this.currWidget = null,
        this.currInfo = this.templateForm
        const form = this.currInfo.form
        this.addExtraInfo(form, '')
        
        return 
      }
      this.currWidget = widget
      let currWidgetInfo = this.$refs.templateMain.__getWidgetInfo(this.currWidget)
      let form = {
        ...currWidgetInfo
      }
      // 补全额外原始信息
      this.addExtraInfo(form, `${currWidgetInfo.areaId}-${currWidgetInfo.z}`)
      this.currInfo = {
        areaId: `${currWidgetInfo.areaId}-${currWidgetInfo.z}`,
        form
      }
    },
    addExtraInfo(form, areaId) {
      if(!form){
        return
      }
      form.tagList = this.self_form.tagList
      this.currProgramMedia = null
      const type = areaId.split('-')[0]
      switch(type) {
        case '':
          this.$set(form, 'type', this.self_form.type || 1)
          if(!this.self_form.type) {
            this.$set(this.self_form, 'type', 1)
          }
          break
        case 'Background':
          form.bgimg = this.widgetMap[areaId].bgimg
          break
        case 'Weather':
          form.weatherAttr = this.widgetMap[areaId].weatherAttr
          break
        case 'Date':
          form.clockAttr = this.widgetMap[areaId].clockAttr
          break
        case 'Time':
          form.timerAttr = this.widgetMap[areaId].timerAttr
          break
        default:
      }
      console.log('------this.programMedia', this.programMedia, areaId)
      let _pm = this.programMedia.find(item => item.areaId === areaId)
      if (_pm) this.currProgramMedia = _pm
    },
    initTemplateInfo({argus, name, type, width, height, id}) {
      this.self_form.templateId = id
      if(this.opType === '1') {
        // 节目名称默认和模板名称相同
        this.self_form.name = name? name.replace(/\.tpl$/, '') : ''
      }
      this.$refs.templateMain.__resetWidget()
      this.templateForm = {
        areaId: '',
        form: {
          areaId: '',
          name,
          type,
          width,
          height
        }
      }
      this.widgetClick(false)
      this.twidget = JSON.parse(argus)
      this.templateOpts = {
        width,
        height
      }
    },
    _openTempDialog() {
      this.temDialog = {
        ...this.temDialog,
        show: true
      }
    },
    updateVisible(v) {
      this.$emit('update:visible', v)
    },
    okClick(v) {
      if (this._vali_self_form()) {
        this.fetching = true
        let form = {
          ...this.self_form,
          programMedia: this.programMedia
        }
        if (this.opType === '1') {
          this._check_programMedia(() => {
            this.$emit('addClick', form, this.fetchingEndCb)
          })
        } else if (this.opType === '2') {
          this._check_programMedia(() => {
            if (form.refCount) {
              this.$confirm('提示', '节目已被使用,需要级联更新否?').then(bool => { 
                form.cascade = bool ? 1 : 0
                this.$emit('updateClick', form, this.fetchingEndCb)
              })
            } else {
               this.$emit('updateClick', form, this.fetchingEndCb)
            }
          })
        } else if (this.opType === '3') {
          if (!form.folderId && form.folderId !== 0) return this.$alert('提示', '请选择目录')
          this._check_programMedia(() => {
            this.$emit('saveClick', form, this.fetchingEndCb)
          })
        } else {
          this.updateVisible(false)
          this.fetchingEndCb()
        }
      }
    },
    _check_programMedia(okcb) {
      const noListArea = []
      this.programMedia.forEach(item => {
        if (item.mediaArgus.length < 1) {
          noListArea.push(widgetNameMap[item.areaId.split('-')[0]])
        }
      })
      if (noListArea.length > 0) {
        this.$confirm('提示', `${noListArea.join('、')} 没有列表是否继续`).then(bool => {
          bool && okcb && okcb()
        })
      } else {
        okcb && okcb()
      }
    },
    _vali_self_form() {
      const { templateId, name, tagList } = this.self_form
      if (!name) {
        this.$message.error('节目名称不能为空')
        return false
      }
      if (!templateId) {
       this.$message.error('请选择模板')
        return false
      }
      // if (tagList.length < 1) {
      //   this.$alert('提示', '请选择标签')
      //   return false
      // }

      return true
    },
    preClick() {

    },
    fetchingEndCb(bool) {
      this.fetching = false
      !bool && this.updateVisible(false)
    },
    cancelClick() {
      this.updateVisible(false)
    }
  },
  created() {
    const TagEventName = this.id ? `tagChange-${this.id}` : 'tagChange'
    const TypeEventName = this.id ? `programTypeChange-${this.id}` : 'programTypeChange'
    this.$eventBus.$on(TagEventName, (v) => {
      console.log(v, '-----tagChange')
      this.self_form.tagList = v.slice()
      this.currInfo.form = {
        ...this.currInfo.form,
        tagList: v.slice()
      }
    })
    this.$eventBus.$on(TypeEventName, (v) => {
      console.log(v, '---v')
      this.self_form.type = v
    })
  },
  beforeDestroy() {
    const TagEventName = this.id ? `tagChange-${this.id}` : 'tagChange'
    const TypeEventName = this.id ? `programTypeChange-${this.id}` : 'programTypeChange'
    this.$eventBus.$off(TagEventName)
    this.$eventBus.$off(TypeEventName)
  }
}
</script>

<style lang="scss" scoped>
// import '@/styles/bs-common.scss';

  $info-row-h: 57px;
  $border-style: 1px solid $bg-e9;

  ::v-deep .el-select-tree {
    width: 200px;
  }

  .showDialog {
    ::v-deep .el-dialog__body {
      padding: 0 !important;
    }

    ::v-deep .el-dialog__header {
      border-bottom: $border-style;
    }
  }

  .show-box {
    display: flex;
    align-items: stretch;

    .left {
      flex: 1;
      padding: 0 20px 20px 20px;
      .info-row {
        height: $info-row-h;
        display: flex;
        align-items: center;
        justify-content: flex-start;
        width: 580px;

        .show-name-input {
          flex-grow: 1;
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 313px;
          margin-right: 16px;
        }

      }

      .temp-panel {
        width: 580px;
        height: 580px;
        border: $border-style;
      }


    }

    .right {
      flex-basis: 280px;
      border-left: $border-style;
      overflow: hidden;

      .attr-title {
        background: $bg-f9;
        border-bottom: $border-style;
        padding-left: 20px;
        line-height: 48px;
        font-size: $font-size-16;
        color: $bg-33;
      }

      .element-name {
        font-size: $font-size-14;
        color: $bg-33;
        padding-left: 20px;
        height: 44px;
        line-height: 44px;
        border-bottom: $border-style;
      }

    }
  }
</style>